import i18n from 'i18next';
import React from 'react';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
import homeCopies from './home.json';
import { useSearchParams } from 'react-router-dom';

const translationFiles = {
    home: homeCopies,
};

const ENTranslationFiles = { ...translationFiles };
Object.entries(ENTranslationFiles).forEach(([key, value]) => {
    ENTranslationFiles[key] = value.en;
});

const ZHTranslationFiles = { ...translationFiles };
Object.entries(ZHTranslationFiles).forEach(([key, value]) => {
    ZHTranslationFiles[key] = value.zh;
});

i18n.use(LanguageDetector)
    .use(initReactI18next) // bind react-i18next to the instance
    .init({
        fallbackLng: 'zh',
        debug: false,
        resources: {
            en: ENTranslationFiles,
            zh: ZHTranslationFiles,
        },
        returnObjects: true,
        interpolation: {
            escapeValue: false, // not needed for react!!
        },
    });

export const useParamAsLanguage = () => {
    // Change site language based on search params.
    const [searchParams, setSearchParams] = useSearchParams();

    const lng = searchParams.get('lng');
    React.useEffect(() => {
        if (lng !== i18n.language) {
            if (lng === 'zh' || lng === 'en') {
                i18n.changeLanguage(lng);
            }
        }
    }, [lng]);
};

export default i18n;
